<?php

declare(strict_types=1);
namespace App\Application\Admin\Controller;
use App\Annotation\Api;
use App\Annotation\View;
use App\Application\Admin\Middleware\AdminMiddleware;
use App\Application\Admin\Model\Goodstype;
use App\Controller\AbstractController;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middleware;
use App\Application\Admin\Model\Goods;
use App\Application\Admin\Model\Store;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Database\Model\Relations\Relation;
use Hyperf\DbConnection\Model\Model;

#[Middleware(AdminMiddleware::class)]
#[Controller("admin/goods")]
class GoodsController extends AbstractController
{
    #[View]
    #[GetMapping("index")]
    public function index()
    {

    }

    #[Api]
    #[GetMapping("index/lists")]
    function lists()
    {
        $where = [];
        $goods_name = $this->request->input('name', '');

        if ($goods_name != '') {
            $where[] = ['name', 'like', '%' . $goods_name . '%'];
        }
        $lists = Goods::where($where)
            ->orderBy('goods_id', 'DESC')
            ->paginate();
        return compact('lists');
    }

    #[Api]
    #[RequestMapping("edit", ["POST", "PUT"])]
    function submitEdit()
    {


        $goods_id = $this->request->input('goods_id', '');
        $name = $this->request->input('name', '');
        $price = $this->request->input('price', '');
        $image_url = $this->request->input('image_url', '');
        $status = $this->request->input('status', '');
        $goods_type_id = $this->request->input('goods_type_id', '');
        $total = $this->request->input('total', '0');
        $content = $this->request->input('content', '');
        $res = Goods::createGoods($goods_id, [
            'name' => $name
            , 'price' => $price
            , 'image_url' => $image_url
            , 'status' => $status
            , 'goods_type_id' => $goods_type_id
            , 'total' => $total
            , 'content' => $content
        ]);

        return $res ? $this->returnSuccessJson(compact('res')) : $this->returnErrorJson();
    }

    #[View]
    #[GetMapping("edit")]
    function edit()
    {
        $goods_id = (int)$this->request->input('goods_id', 0);

        return ['title' => $goods_id > 0 ? '编辑套餐' : '新增套餐'];
    }


    #[Api]
    #[GetMapping("edit/{goods_id}")]
    function editInfo(int $goods_id)
    {


        $goods = Goods::where('goods_id', $goods_id)->select('*')
            ->first() ?: [];
        $labelOptions = Goodstype::where('deleted_at', null)
            ->orderBy('created_at')
            ->select([
                'goods_type_id', 'name'
            ])
            ->get()
            ->toArray();
        if ($goods_id !== 0) {

            $goods['store_name'] = Store::where('store_id', $goods['store_id'])->value('name')
                ?: [];

        }

        return compact('goods', 'labelOptions');
    }


}
